package cn.wolfcode.p2p.base.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
// session 类
public class LoginInfoContext {
    private static final String LOGININFO_IN_SESSION_KEY = "loginInfo";
    private static final String VERIFY_CODE_IN_SESSION = "verify_code_in_session";

    /**
     * 获取当前请求的ip地址
     * @return ip地址
     */
    public static String getCurrentRequestIp(){
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes()))
                .getRequest().getRemoteAddr();
    }

    private static HttpSession getSession() {
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes()))
                .getRequest().getSession();
    }

    //------------------------------------------------------------------------------------

    /**
     * 把登录成功的用户对象存进session
     * @param loginInfo 用户对象
     */
    public static void setCurrentLoginInfo(LoginInfo loginInfo) {
        if (loginInfo != null){
            getSession().setAttribute(LOGININFO_IN_SESSION_KEY,loginInfo);
        } else {
            // 当参数为 null 时, 移除当前属性
            getSession().removeAttribute(LOGININFO_IN_SESSION_KEY);
        }

    }

    /**
     * 获取登录时存储的登录对象
     * @return
     */
    public static LoginInfo getCurrentLoginInfo() {
        return (LoginInfo) getSession().getAttribute(LOGININFO_IN_SESSION_KEY);
    }

    //------------------------------------------------------------------------------------

    /**
     * 把验证码的vo对象存进session
     * @param vo
     */
    public static void setVerifyCode(VerifyCodeVO vo){
        if (vo != null){
            getSession().setAttribute(VERIFY_CODE_IN_SESSION, vo);
        } else {
            // 当参数为 null 时, 移除当前属性
            getSession().removeAttribute(VERIFY_CODE_IN_SESSION);
        }

    }

    /**
     * 获取session中的验证码的vo对象
     * @return
     */
    public static VerifyCodeVO getVerifyCode(){
        return (VerifyCodeVO) getSession().getAttribute(VERIFY_CODE_IN_SESSION);
    }
}
